import { createSlice ,createAsyncThunk} from "@reduxjs/toolkit";
import * as API from '../api/http'
const initialState={
    shoplist:[],
    typelist:[]
}
const todosSlice = createSlice({
  name: "todos",
  initialState,
  reducers: {
    t_getshoplist(state, action) {
      state.shoplist=action.payload
    },
    t_delshoplist(state, action) {
      state.shoplist=state.shoplist.filter(item=>{
        return item.id!==action.payload
      })
    },
    t_addshoplist(state, action) {
      state.shoplist.push(action.payload)
    },
    t_editshoplist(state, action) {
      let i=state.shoplist.findIndex(item=>{
        return item.id==action.payload.id
      })
      state.shoplist[i]=action.payload
    },
  },
});

export const actionfn = todosSlice.actions;
export default todosSlice.reducer;
//异步
export let async_getshoplist=createAsyncThunk("async_getshoplist",async(_,store)=>{
    let res=await API.http_get()
    store.dispatch(actionfn.t_getshoplist(res))
})
//删除
export let async_delshoplist=createAsyncThunk("async_delshoplist",async(id,store)=>{
    await API.http_del(id)
    store.dispatch(actionfn.t_delshoplist(id))
})
//添加
export let async_addshoplist=createAsyncThunk("async_addshoplist",async(obj,store)=>{
    let res=await API.http_add(obj)
    store.dispatch(actionfn.t_addshoplist(res))
})
//编辑
export let async_editshoplist=createAsyncThunk("async_editshoplist",async(obj,store)=>{
    let res=await API.http_edit(obj)
    store.dispatch(actionfn.t_editshoplist(res))
})